﻿using Common.Class;
using Common.Model;

namespace BLL
{
    public class SessionBLL
    {

        public static List<SessionModel> SessionList = null;

        public static string LoginPassword = "";

        /// <summary>
        /// 获取所有会话对象
        /// </summary>
        /// <returns></returns>
        public static List<SessionModel> SessionListGet()
        {
            string _s = StringHelper.Decompress(FileHelper.FileTextRead(FileHelper.GetRunPath() + @"\SessionInfo"));
            JsonHelper _json = new JsonHelper(EncryptHelper.DecryptString_Aes(_s, "JLSoft"));
            LoginPassword = _json.GetVar("LoginPassword");
            List<SessionModel> _sessionList = JsonHelper.GetObjectFromJsonStr<List<SessionModel>>(_json.GetVar("SessionList"));
            if (_sessionList == null)
            {
                _sessionList = new List<SessionModel>();
            }
            SessionList = _sessionList;
            return _sessionList;
        }

        /// <summary>
        /// 保持会话数据
        /// </summary>
        /// <param name="modelList"></param>
        public static void SessionListSave(List<SessionModel> modelList)
        {
            SessionList = modelList;
            string _sessionList = JsonHelper.GetJsonStrFromObject(modelList);
            string _json = new JsonHelper()
                .AddVar("SessionList", _sessionList)
                .AddVar("LoginPassword", LoginPassword)
                .JsonStr;
            string _data = EncryptHelper.EncryptString_Aes(_json, "JLSoft");
            string _sZip = StringHelper.Compress(_data);
            FileHelper.FileTextWrite(FileHelper.GetRunPath() + @"\SessionInfo", _sZip);
        }

        /// <summary>
        /// 根据会话ID获取会话数据和父节点会话
        /// </summary>
        /// <param name="sessionList"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static (SessionModel session, SessionModel fSession) SessionGetFromID(List<SessionModel> sessionList, long id)
        {
            foreach (SessionModel session in sessionList)
            {
                SessionModel _fSession = null;
                if (session.ID == id)
                {
                    return (session, _fSession);
                }

                if (session.ChildSessionList != null && session.ChildSessionList.Count > 0)
                {
                    var _result = SessionGetFromID(session.ChildSessionList, id);
                    if (_result.session != null)
                    {
                        if (_result.fSession == null)
                        {
                            return (_result.session, session);
                        }
                        else
                        {
                            return (_result.session, _result.fSession);
                        }
                    }
                }


            }
            return (null, null);
        }



    }
}
